package com.cefa.edu.service;

import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSONObject;
import com.cefa.edu.common.ConstantProperties;
import com.cefa.edu.dao.*;
import com.cefa.edu.pojo.User;
import com.cefa.edu.pojo.BlockChainData;
import com.cefa.edu.pojo.Phase;
import com.cefa.edu.pojo.Score;
import com.cefa.edu.pojo.UserOrganRole;
import com.cefa.edu.util.HttpRequestUtil;
import com.cefa.edu.vo.GradeBean;
import com.cefa.edu.vo.StageBean;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by cc664 on 2018/8/3.
 */
@Service
public class ScoreService {
    @Autowired
    private ScoreMapper scoreMapper;
    @Autowired
    PhaseMapper phaseMapper;
    @Autowired
    UserOrganRoleMapper userOrganRoleMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    BlockChainDataMapper blockChainDataMapper;
    @Autowired
    ScoreService scoreService;
    @Autowired
    ConstantProperties constantProperties;
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //遍历成绩数据 把不同学段的数据封装到不同的集合中
    public  HashMap<String,List<HashMap<String,Object>>> HandleScoreMapList(List<HashMap<String,Object>> scoreMapList,Integer schoolId){
        //senior(eduStageId=4) junior(eduStageId=3) primary(eduStageId=2) kindergarten(eduStageId=1)
        Integer eduStageId=null;
        Object keyValue=null;

        List<HashMap<String,Object>> kindergartenList=new ArrayList<HashMap<String,Object>>();//幼儿园成绩
        List<HashMap<String,Object>> primaryList=new ArrayList<HashMap<String,Object>>();//小学成绩
        List<HashMap<String,Object>> juniorList=new ArrayList<HashMap<String,Object>>();//初中成绩
        List<HashMap<String,Object>> seniorList=new ArrayList<HashMap<String,Object>>();//高中成绩

        //获取所有教育阶段编号
        Map<String,String> phaseIdMap=this.getAllPhaseIdBySchoolId(schoolId);
        Integer kindergartenPhaseId=null;
        Integer primaryPhaseId=null;
        Integer juniorPhaseId=null;
        Integer seniorPhaseId=null;

        if(phaseIdMap!=null && phaseIdMap.size()>0){
             kindergartenPhaseId=phaseIdMap.get("kindergartenPhaseId")!=null?Integer.parseInt(phaseIdMap.get("kindergartenPhaseId")):null;
             primaryPhaseId=phaseIdMap.get("primaryPhaseId")!=null?Integer.parseInt(phaseIdMap.get("primaryPhaseId")):null;
             juniorPhaseId=phaseIdMap.get("juniorPhaseId")!=null?Integer.parseInt(phaseIdMap.get("juniorPhaseId")):null;
             seniorPhaseId=phaseIdMap.get("seniorPhaseId")!=null?Integer.parseInt(phaseIdMap.get("seniorPhaseId")):null;
        }

        for(HashMap<String,Object> soreMap:scoreMapList){
            keyValue=soreMap.get("eduStageId");
            eduStageId=Integer.parseInt(keyValue.toString());

            if(kindergartenPhaseId!=null){
                if(eduStageId.equals(kindergartenPhaseId)){
                    kindergartenList.add(soreMap);
                }
            }
            if(primaryPhaseId!=null){
                if(eduStageId.equals(primaryPhaseId)){
                    primaryList.add(soreMap);
                }
            }
            if(juniorPhaseId!=null){
                if(eduStageId.equals(juniorPhaseId)){
                    juniorList.add(soreMap);
                }
            }
            if(seniorPhaseId!=null){
                if(eduStageId.equals(seniorPhaseId)){
                    seniorList.add(soreMap);
                }
            }

        }//for(HashMap<String,Object> soreMap:scoreMapList)

        //封装到Map中 返回
        HashMap<String,List<HashMap<String,Object>>> handleMap=new HashMap<String,List<HashMap<String,Object>>>();
        if(kindergartenList.size()>0){
            handleMap.put("kl",kindergartenList);
        }
        if(primaryList.size()>0){
            handleMap.put("pl",primaryList);
        }
        if(juniorList.size()>0){
            handleMap.put("jl",juniorList);
        }
        if(seniorList.size()>0){
            handleMap.put("sl",seniorList);
        }
        return handleMap;

    }

    //获取指定学校的所有教育阶段编号
    private Map<String,String> getAllPhaseIdBySchoolId(Integer schoolId) {

        List<HashMap<String,Object>> phaseMapList= phaseMapper.getPhasesBySchoolId(schoolId);
        if(phaseMapList!=null && phaseMapList.size()>0){
            Map<String,String> phaseIdMap=Maps.newHashMap();

            for(HashMap<String,Object> map:phaseMapList){
                String phaseName= map.get("phaseName")!=null?map.get("phaseName").toString():null;
                if("高中".equals(phaseName)){
                    phaseIdMap.put("seniorPhaseId",map.get("id")!=null?map.get("id").toString():null);
                }
                if("初中".equals(phaseName)){
                    phaseIdMap.put("juniorPhaseId",map.get("id")!=null?map.get("id").toString():null);
                }
                if("小学".equals(phaseName)){
                    phaseIdMap.put("primaryPhaseId",map.get("id")!=null?map.get("id").toString():null);
                }
                if("幼儿园".equals(phaseName)){
                    phaseIdMap.put("kindergartenPhaseId",map.get("id")!=null?map.get("id").toString():null);
                }
            }
            return phaseIdMap;
        }
        return  null;
    }


    /**
     * @aa 根据userId获取对应的各个阶段成绩数据 封装到StScoreBean对象中
     * @param userId
     * @return
     */
    public   List<StageBean> getStagesScoresByUserId(Integer userId,Integer schoolId){

        /**
         * @aa 操作
         * @aa 1、根据userId获取所有学段的成绩数据
         * @aa 2、遍历成绩数据 把不同学段的数据封装到不同的集合中
         * @aa 3、把封装不同学段成绩的集合 封装到StScoreBean对象中返回
         */
        List<StageBean> stageBeanList=null;
        List<HashMap<String,Object>> scoreMapList= scoreMapper.getScoresByUserId(userId);
        if(scoreMapList!=null && scoreMapList.size()>0){
            //遍历成绩数据 把不同学段的数据封装到不同的集合中
            HashMap<String,List<HashMap<String,Object>>> handleMap=this.HandleScoreMapList(scoreMapList,schoolId);

            List<HashMap<String,Object>> kindergartenList=handleMap.get("kl");
            if(kindergartenList!=null && kindergartenList.size()>0){
                stageBeanList =this.packageData2StageBeanBean(stageBeanList,kindergartenList,1);
            }

            List<HashMap<String,Object>> primaryList=handleMap.get("pl");
            if(primaryList!=null && primaryList.size()>0){
                stageBeanList =this.packageData2StageBeanBean(stageBeanList,primaryList,2);
            }

            List<HashMap<String,Object>> juniorList=handleMap.get("jl");
            if(juniorList!=null && juniorList.size()>0){
                stageBeanList =this.packageData2StageBeanBean(stageBeanList,juniorList,3);
            }

            List<HashMap<String,Object>> seniorList=handleMap.get("sl");
            if(seniorList!=null && seniorList.size()>0){
                stageBeanList =this.packageData2StageBeanBean(stageBeanList,seniorList,4);
            }

            return stageBeanList;
        }
        return null;

    }

    //把数据封装到stageBeanList
    private List<StageBean> packageData2StageBeanBean(List<StageBean> stageBeanList, List<HashMap<String, Object>> scorelist, int stageId) {

        if(stageBeanList==null){
            stageBeanList =new ArrayList<StageBean>();
        }
        if( scorelist!=null && scorelist.size()>0){
            //把成绩以年级分类 封装到map中
            StageBean stageBean=null;
            List<GradeBean> gradeList=null;
            switch (stageId){
                case 1:
                    stageBean=new StageBean();
                    stageBean.setStageId(stageId);
                    stageBean.setStageName("幼儿园");

                    //把成绩数据 封装到年级集合中
                    gradeList=this.handleScoresDataForGrageBeans(scorelist,stageId);
                    stageBean.setGrades(gradeList);
                    stageBeanList.add(stageBean);

                    // stScoreBean.setKindergarten(kindergarten);
                    break;
                case 2:
                    stageBean=new StageBean();
                    stageBean.setStageId(stageId);
                    stageBean.setStageName("小学");
                    //把成绩数据 封装到年级集合中
                    gradeList=this.handleScoresDataForGrageBeans(scorelist,stageId);
                    stageBean.setGrades(gradeList);
                    stageBeanList.add(stageBean);
                    break;
                case 3:
                    stageBean=new StageBean();
                    stageBean.setStageId(stageId);
                    stageBean.setStageName("初中");
                    //把成绩数据 封装到年级集合中
                    gradeList=this.handleScoresDataForGrageBeans(scorelist,stageId);
                    stageBean.setGrades(gradeList);
                    stageBeanList.add(stageBean);

                    break;
                case 4:
                    stageBean=new StageBean();
                    stageBean.setStageId(stageId);
                    stageBean.setStageName("高中");
                    //把成绩数据 封装到年级集合中
                    gradeList=this.handleScoresDataForGrageBeans(scorelist,stageId);
                    stageBean.setGrades(gradeList);
                    stageBeanList.add(stageBean);

                    break;
            }

        }
        return stageBeanList;
    }


    //把成绩数据 封装到年级集合中
    private List<GradeBean> handleScoresDataForGrageBeans(List<HashMap<String, Object>> scoresList, int stageId ) {

        List<GradeBean> gradeBeanList=new ArrayList<GradeBean>();
        Object gradeName=null;
        Integer gradeId=null;

        if(scoresList!=null && scoresList.size()>0){

            GradeBean  gradeOneBean=new GradeBean();
            GradeBean  gradeTwoBean=new GradeBean();
            GradeBean  gradeThreeBean=new GradeBean();
            GradeBean  gradeFourBean=new GradeBean();
            GradeBean  gradeFiveBean=new GradeBean();
            GradeBean  gradeSixBean=new GradeBean();
            List<Map<String,Object>> gradeOneScoreList=null;
            List<Map<String,Object>> gradeTwoScoreList=null;
            List<Map<String,Object>> gradeThreeScoreList=null;
            List<Map<String,Object>> gradeFourScoreList=null;
            List<Map<String,Object>> gradeFiveScoreList=null;
            List<Map<String,Object>> gradeSixScoreList=null;

            switch (stageId){
                case 1:
                    //幼儿园
                    for(HashMap<String,Object> scoreMap:scoresList){
                        gradeName= scoreMap.get("gradeName");
                        gradeId=Integer.parseInt(scoreMap.get("grade_id").toString());
                        if("小班".equals(gradeName)){
                            if(gradeOneScoreList==null){
                                gradeOneScoreList=new ArrayList<Map<String,Object>>();
                            }
                            gradeOneBean.setGradeId(gradeId);
                            gradeOneBean.setGradeName("小班");
                            gradeOneScoreList.add(scoreMap);
                        }
                        if("中班".equals(gradeName)){
                            if(gradeTwoScoreList==null){
                                gradeTwoScoreList=new ArrayList<Map<String,Object>>();
                            }
                            gradeTwoBean.setGradeId(gradeId);
                            gradeTwoBean.setGradeName("中班");
                            gradeTwoScoreList.add(scoreMap);
                        }
                        if("大班".equals(gradeName)){
                            if(gradeThreeScoreList==null){
                                gradeThreeScoreList=new ArrayList<Map<String,Object>>();
                            }
                            gradeThreeBean.setGradeId(gradeId);
                            gradeThreeBean.setGradeName("中班");
                            gradeThreeScoreList.add(scoreMap);
                        }
                        if("学前".equals(gradeName)){
                            if(gradeFourScoreList==null){
                                gradeFourScoreList=new ArrayList<Map<String,Object>>();
                            }
                            gradeFourBean.setGradeId(gradeId);
                            gradeFourBean.setGradeName("中班");
                            gradeFourScoreList.add(scoreMap);
                        }
                    }//for(HashMap<String,Object> scoreMap:scoresList)
                    break;
                case 2:
                    //小学 6个年级
                    for(HashMap<String,Object> scoreMap:scoresList){
                        gradeName= scoreMap.get("gradeName");
                        gradeId=Integer.parseInt(scoreMap.get("grade_id").toString());

                        if("一年级".equals(gradeName)){
                            if(gradeOneScoreList==null){
                                gradeOneScoreList=new ArrayList<Map<String,Object>>();
                            }
                            gradeOneBean.setGradeId(gradeId);
                            gradeOneBean.setGradeName("一年级");
                            gradeOneScoreList.add(scoreMap);
                        }
                        if("二年级".equals(gradeName)){
                            if(gradeTwoScoreList==null){
                                gradeTwoScoreList=new ArrayList<Map<String,Object>>();
                            }
                            gradeTwoBean.setGradeId(gradeId);
                            gradeTwoBean.setGradeName("二年级");
                            gradeTwoScoreList.add(scoreMap);
                        }
                        if("三年级".equals(gradeName)){
                            if(gradeThreeScoreList==null){
                                gradeThreeScoreList=new ArrayList<Map<String,Object>>();
                            }
                            gradeThreeBean.setGradeId(gradeId);
                            gradeThreeBean.setGradeName("三年级");
                            gradeThreeScoreList.add(scoreMap);
                        }

                        if("四年级".equals(gradeName)){
                            if(gradeFourScoreList==null){
                                gradeFourScoreList=new ArrayList<Map<String,Object>>();
                            }
                            gradeFourBean.setGradeId(gradeId);
                            gradeFourBean.setGradeName("四年级");
                            gradeFourScoreList.add(scoreMap);
                        }
                        if("五年级".equals(gradeName)){
                            if(gradeFiveScoreList==null){
                                gradeFiveScoreList=new ArrayList<Map<String,Object>>();
                            }
                            gradeFiveBean.setGradeId(gradeId);
                            gradeFiveBean.setGradeName("五年级");
                            gradeFiveScoreList.add(scoreMap);
                        }
                        if("六年级".equals(gradeName)){
                            if(gradeSixScoreList==null){
                                gradeSixScoreList=new ArrayList<Map<String,Object>>();
                            }
                            gradeSixBean.setGradeId(gradeId);
                            gradeSixBean.setGradeName("六年级");
                            gradeSixScoreList.add(scoreMap);
                        }
                    }

                    break;
                case 3:
                    //初中阶段 3个年级
                    for(HashMap<String,Object> scoreMap:scoresList){
                        gradeName= scoreMap.get("gradeName");
                        gradeId=Integer.parseInt(scoreMap.get("grade_id").toString());
                        if("初一".equals(gradeName)){
                            if(gradeOneScoreList==null){
                                gradeOneScoreList=new ArrayList<Map<String,Object>>();
                            }
                            gradeOneBean.setGradeId(gradeId);
                            gradeOneBean.setGradeName("初一");
                            gradeOneScoreList.add(scoreMap);
                        }
                        if("初二".equals(gradeName)){
                            if(gradeTwoScoreList==null){
                                gradeTwoScoreList=new ArrayList<Map<String,Object>>();
                            }
                            gradeTwoBean.setGradeId(gradeId);
                            gradeTwoBean.setGradeName("初二");
                            gradeTwoScoreList.add(scoreMap);
                        }
                        if("初三".equals(gradeName)){
                            if(gradeThreeScoreList==null){
                                gradeThreeScoreList=new ArrayList<Map<String,Object>>();
                            }
                            gradeThreeBean.setGradeId(gradeId);
                            gradeThreeBean.setGradeName("初三");
                            gradeThreeScoreList.add(scoreMap);
                        }
                    }

                    break;
                case 4:
                    //高中阶段 3个年级
                    for(HashMap<String,Object> scoreMap:scoresList){
                        gradeName= scoreMap.get("gradeName");
                        gradeId=Integer.parseInt(scoreMap.get("grade_id").toString());
                        if("高一".equals(gradeName)){
                            if(gradeOneScoreList==null){
                                gradeOneScoreList=new ArrayList<Map<String,Object>>();
                            }
                            gradeOneBean.setGradeId(gradeId);
                            gradeOneBean.setGradeName("高一");
                            gradeOneScoreList.add(scoreMap);
                        }
                        if("高二".equals(gradeName)){
                            if(gradeTwoScoreList==null){
                                gradeTwoScoreList=new ArrayList<Map<String,Object>>();
                            }
                            gradeTwoBean.setGradeId(gradeId);
                            gradeTwoBean.setGradeName("高二");
                            gradeTwoScoreList.add(scoreMap);
                        }
                        if("高三".equals(gradeName)){
                            if(gradeThreeScoreList==null){
                                gradeThreeScoreList=new ArrayList<Map<String,Object>>();
                            }
                            gradeThreeBean.setGradeId(gradeId);
                            gradeThreeBean.setGradeName("高三");
                            gradeThreeScoreList.add(scoreMap);
                        }
                    }
                    break;
            }
            //封装分数集合到年级bean中
            if(gradeOneScoreList!=null &&gradeOneScoreList.size()>0){
                gradeOneBean.setTestScores(gradeOneScoreList);
                gradeBeanList.add(gradeOneBean);//封装年级到集合中
            }
            //封装分数集合到年级bean中
            if(gradeTwoScoreList!=null &&gradeTwoScoreList.size()>0){
                gradeTwoBean.setTestScores(gradeTwoScoreList);
                gradeBeanList.add(gradeTwoBean);//封装年级到集合中
            }
            //封装分数集合到年级bean中
            if(gradeThreeScoreList!=null &&gradeThreeScoreList.size()>0){
                gradeThreeBean.setTestScores(gradeThreeScoreList);
                gradeBeanList.add(gradeThreeBean);//封装年级到集合中
            }
            //封装分数集合到年级bean中
            if(gradeFourScoreList!=null &&gradeFourScoreList.size()>0){
                gradeFourBean.setTestScores(gradeFourScoreList);
                gradeBeanList.add(gradeFourBean);//封装年级到集合中
            }
            //封装分数集合到年级bean中
            if(gradeFiveScoreList!=null &&gradeFiveScoreList.size()>0){
                gradeFiveBean.setTestScores(gradeFiveScoreList);
                gradeBeanList.add(gradeFiveBean);//封装年级到集合中
            }
            //封装分数集合到年级bean中
            if(gradeSixScoreList!=null &&gradeSixScoreList.size()>0){
                gradeSixBean.setTestScores(gradeSixScoreList);
                gradeBeanList.add(gradeSixBean);//封装年级到集合中
            }

            return gradeBeanList;
        }//if(scoresList!=null && scoresList.size()>0)
        return  null;
    }

    /**
     * 按照时间（升序）、分数排序（降序）
     * 根据学段id、学生id 获取学生分数数据
     */
    public List<HashMap<String,Object>> getScoresByUserIdAndEduStageId(Integer userId, Integer eduStageId){
        return scoreMapper.getScoresByUserIdAndEduStageId(userId,eduStageId);
    }


    /**
     * 可以根据权限查询不同上链状态的学生成绩数据
     * @param userId
     * @param roleType
     * @param chainStatus
     * @param schoolId
     * @return
     */
    @Transactional("transactionManager")
    public Map<Integer,List<Score>>  studentChainData(Integer userId, Integer roleType, Integer chainStatus, Integer schoolId,Integer pageNo,Integer pageCount) {
        //1、首先查看登录用户什么角色，如果是admin，则查询所有的学生成绩表+chainStatus
        //2、如果是教育阶段管理者，查询成绩表时 education_stage_id in (根据用户id查询是年级管理者角色的人的阶段id group by 教育阶段id)+chainStatus
        //3、如果还是年级管理者，并且该年级不在2中的教育阶段，则grade_id in (根据用户id查询是年级管理者角色的人的年级id group by 年级id) +chainStatus
        //4、如果即是教育阶段管理者也是年级管理者 education_stage_id in () or  grade_id in () +chainStatus
        //5、如果即时老师还是管理者 education_stage_id in () or  grade_id in () or level_id in （根据用户id和老师角色查询 group by 班级id）+chainStatus
        List<Score> scores=null;
        Map<Integer,List<Score>> map=new HashMap<>();
        Integer count=0;
        StringBuilder phaseIds = new StringBuilder();
        StringBuilder gradeIds = new StringBuilder();
        StringBuilder classIds = new StringBuilder();
        StringBuilder courseIds = new StringBuilder();
        if(roleType==1){//admin
            List<Phase> list=phaseMapper.findPhaseListBySchoolId(schoolId);
            for (Phase phase :list){
                phaseIds.append(phase.getId());
                phaseIds.append(",");
            }
            phaseIds.deleteCharAt(phaseIds.length()-1);
            scores=scoreMapper.getScoreByPhaseIds(phaseIds.toString(),chainStatus,(pageNo-1)*pageCount,pageCount,0);
            count=scoreMapper.getScoreByPhaseIdsCount(phaseIds.toString(),chainStatus,0);
        }else if(roleType==2){//教育阶段管理者
            List<UserOrganRole> list1= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,2);//教育阶段id集合
            for (UserOrganRole userOrganRole:list1){
                phaseIds.append(userOrganRole.getPhaseId());
                phaseIds.append(",");
            }
            phaseIds.deleteCharAt(phaseIds.length()-1);


            List<UserOrganRole> list2= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,3);//年级id集合
            for (UserOrganRole userOrganRole:list2){
                gradeIds.append(userOrganRole.getGradeId());
                gradeIds.append(",");
            }
            if(gradeIds.length()>0){
                gradeIds.deleteCharAt(gradeIds.length()-1);
            }



            List<UserOrganRole> list3= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,4);//班级id集合
            for (UserOrganRole userOrganRole:list3){
                classIds.append(userOrganRole.getClassId());
                classIds.append(",");
            }
            if(classIds.length()>0){
                classIds.deleteCharAt(classIds.length()-1);
            }


            List<UserOrganRole> list4= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,5);//科目id集合
            for (UserOrganRole userOrganRole:list4){
                courseIds.append(userOrganRole.getCourseId());
                courseIds.append(",");
            }
            if(courseIds.length()>0){
                courseIds.deleteCharAt(courseIds.length()-1);
            }
            List<UserOrganRole> list5=null;
            int status=0;
            Integer levelCount=0;
            if(gradeIds.length()>0&&classIds.length()>0){//同时是一层管理者和二层管理者、班主任(任课老师)
                status=1;
            }else if(gradeIds.length()==0&&classIds.length()>0){//只是一层管理者和班主任(任课老师)
                status=2;
            }else if(gradeIds.length()>0&&classIds.length()==0){//只是一层管理者、二层管理者
                status=3;
            }else if(gradeIds.length()==0&&classIds.length()==0){//只是一层管理者
                status=4;
            }
            scores=scoreMapper.getScoreByids3(status,classIds.length()>0?classIds.toString():null,courseIds.length()>0?courseIds.toString():null,gradeIds.toString(),phaseIds.toString(),chainStatus,(pageNo-1)*pageCount,pageCount,0);
            count=scoreMapper.getScoreByids3Count(status,classIds.length()>0?classIds.toString():null,courseIds.length()>0?courseIds.toString():null,gradeIds.toString(),phaseIds.toString(),chainStatus,0);
        }else if(roleType==3){//年级管理者
            List<UserOrganRole> list2= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,3);//年级id集合
            for (UserOrganRole userOrganRole:list2){
                gradeIds.append(userOrganRole.getGradeId());
                gradeIds.append(",");
            }
            if(gradeIds.length()>0){
                gradeIds.deleteCharAt(gradeIds.length()-1);
            }


            List<UserOrganRole> list3= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,4);//班级id集合
            for (UserOrganRole userOrganRole:list3){
                classIds.append(userOrganRole.getClassId());
                classIds.append(",");
            }
            if(classIds.length()>0){
                classIds.deleteCharAt(classIds.length()-1);
            }


            List<UserOrganRole> list4= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,5);//科目id集合
            for (UserOrganRole userOrganRole:list4){
                courseIds.append(userOrganRole.getCourseId());
                courseIds.append(",");
            }
            if(courseIds.length()>0){
                courseIds.deleteCharAt(courseIds.length()-1);
            }

            Integer status=0;
            if(classIds.length()>0&&courseIds.length()>0){//二级管理者，还是老师和班主任
                status=1;
            }else if(classIds.length()>0&&courseIds.length()==0){//二级管理者、班主任
                status=3;
            }else if(classIds.length()==0&&courseIds.length()==0){//二级管理者
                status=4;
            }
            scores=scoreMapper.getScoreByids4(status,classIds.length()>0?classIds.toString():null,courseIds.length()>0?courseIds.toString():null,gradeIds.toString(),chainStatus,(pageNo-1)*pageCount,pageCount,0);
            count=scoreMapper.getScoreByids4Count(status,classIds.length()>0?classIds.toString():null,courseIds.length()>0?courseIds.toString():null,gradeIds.toString(),chainStatus,0);
        }else if(roleType==4||roleType==5){//老师(任课老师只能查看所教的课程成绩，班主任可以查看全班级的所有学生成绩)
            List<UserOrganRole> list3= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,4);
            List<UserOrganRole> list4= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,5);
            for(UserOrganRole userOrganRole :list3){
                classIds.append(userOrganRole.getClassId());
                classIds.append(",");
            }
            if(classIds.length()>0){
                classIds.deleteCharAt(classIds.length()-1);
            }

            for(UserOrganRole userOrganRole:list4){
                courseIds.append(userOrganRole.getCourseId());
                courseIds.append(",");
            }
            if(courseIds.length()>0){
                courseIds.deleteCharAt(courseIds.length()-1);
            }
            Integer status=0;
            if(classIds.length()>0&&courseIds.length()>0){
                status=1;
            }else if(classIds.length()>0&&courseIds.length()==0){
                status=2;
            }else if(classIds.length()==0&&courseIds.length()>0){
                status=3;
            }
            scores=scoreMapper.getScoreByids5(status,classIds.length()>0?classIds.toString():null,courseIds.length()>0?courseIds.toString():null,chainStatus,(pageNo-1)*pageCount,pageCount,0);
            count=scoreMapper.getScoreByids5Count(status,classIds.length()>0?classIds.toString():null,courseIds.length()>0?courseIds.toString():null,chainStatus,0);
        }else if(roleType==6){//监护人
            User user =userMapper.getUserById(userId);
            scores=scoreMapper.getScoreByUserId(user.getStudentId(),chainStatus,(pageNo-1)*pageCount,pageCount,0);
            count=scoreMapper.getScoreByUserIdCount(user.getStudentId(),chainStatus,0);
        }else if(roleType==7){
            User user =userMapper.getUserById(userId);
            scores=scoreMapper.getScoreByUserId(user.getId(),chainStatus,(pageNo-1)*pageCount,pageCount,0);
            count=scoreMapper.getScoreByUserIdCount(user.getId(),chainStatus,0);
        }
        map.put(count,scores);
        return map;
    }

    @Transactional("transactionManager")
    public void scoreSign(Integer classId,Integer userId,Integer roleType,Integer scoreId,String signData,String stablejson,String sha3file){


        User user=userMapper.getUserById(userId);
        com.cefa.edu.pojo.Score score= new com.cefa.edu.pojo.Score();
        score.setId(scoreId);
        if(roleType==1){
            score.setManagerCheckName(user.getName()+"(超级管理员)");
            score.setManagerCheckStatus(1);
            score.setManagerCheckSignData(signData);
            scoreMapper.updateScore1(score.getManagerCheckName(),score.getManagerCheckStatus(),score.getManagerCheckSignData(),scoreId);
        }else if(roleType==2){
            score.setManagerCheckName(user.getName()+"(教育阶段管理者)");
            score.setManagerCheckStatus(1);
            score.setManagerCheckSignData(signData);
            scoreMapper.updateScore1(score.getManagerCheckName(),score.getManagerCheckStatus(),score.getManagerCheckSignData(),scoreId);
        }else if(roleType==3){
            score.setManagerCheckName(user.getName()+"(年级管理者)");
            score.setManagerCheckStatus(1);
            score.setManagerCheckSignData(signData);
            scoreMapper.updateScore1(score.getManagerCheckName(),score.getManagerCheckStatus(),score.getManagerCheckSignData(),scoreId);
        }else if(roleType==4){
            score.setInstructorCheckName(user.getName()+"(班主任)");
            score.setInstructorCheckStatus(1);
            score.setInstructorCheckSignData(signData);
            scoreMapper.updateScore2(score.getInstructorCheckName(),score.getInstructorCheckStatus(),score.getInstructorCheckSignData(),scoreId);
        }else if(roleType==5){
            score.setInstructorCheckName(user.getName()+"(任课老师)");
            score.setInstructorCheckStatus(1);
            score.setInstructorCheckSignData(signData);
            scoreMapper.updateScore2(score.getInstructorCheckName(),score.getInstructorCheckStatus(),score.getInstructorCheckSignData(),scoreId);
        }else if(roleType==6){
            score.setGuardianCheckName(user.getName()+"(监护人)");
            score.setGuardianCheckStatus(1);
            score.setGuardianCheckSignData(signData);
            scoreMapper.updateScore3(score.getGuardianCheckName(),score.getGuardianCheckStatus(),score.getGuardianCheckSignData(),scoreId);
        }else if(roleType==7){
            score.setGuardianCheckName(user.getName()+"(学生)");
            score.setGuardianCheckStatus(1);
            score.setGuardianCheckSignData(signData);
            scoreMapper.updateScore3(score.getGuardianCheckName(),score.getGuardianCheckStatus(),score.getGuardianCheckSignData(),scoreId);
        }
        //判断当前用户是否已签名过该成绩  add by chaijian 2018-09-19
        synchronized (scoreId){
            int count= scoreMapper.getSignatureRecordCount(userId,scoreId,roleType);
            if(count==0){
                scoreMapper.insertSignatureRecord(userId,scoreId,roleType);
            }
        }
        Score score1=scoreMapper.getScoreById(scoreId);
        if(score1.getGuardianCheckStatus()==1&&score1.getInstructorCheckStatus()==1&&score1.getManagerCheckStatus()==1){
            List<User> userList=userMapper.getUserListBySchoolId(user.getSchoolId());
            com.cefa.edu.pojo.User user1=userMapper.getUserById(score1.getUserId());//学生用户信息
            JSONObject jsonObject1= new JSONObject();
            jsonObject1.put("stablejson",stablejson);
            jsonObject1.put("sha3file",sha3file);
            jsonObject1.put("stuSigned",score1.getGuardianCheckSignData());
            jsonObject1.put("edu0Signed",score1.getManagerCheckSignData());
            jsonObject1.put("edu1Signed",score1.getInstructorCheckSignData());
            jsonObject1.put("eduPrikey",userList.get(0).getKeyData());
            jsonObject1.put("fileAddress",user1.getFileAddress());
            jsonObject1.put("verificationAddress",user1.getVerificationAddress());

            String chainDataStr=HttpRequestUtil.sendPost(constantProperties.addfilerecord,jsonObject1.toJSONString(),"UTF-8");
            //拿到返回来的数据保存表中
            JSONObject jsonObject= (JSONObject) JSONObject.parseObject(chainDataStr).get("msg");
            BlockChainData chainData = new BlockChainData();
            chainData.setBlockHash(jsonObject.get("blockHash").toString());
            chainData.setBlockHeight(jsonObject.get("blockNumber").toString());
            chainData.setChainTime(sdf.format(new Date()));
            chainData.setDataHash("");
            chainData.setDataId(scoreId);
            chainData.setDataType(1);
            chainData.setTransactionHash(jsonObject.get("transactionHash").toString());

            //一条成绩对应一条上链数据 add by chaijian 2018-09-19
            int count=blockChainDataMapper.getBlockChainDataCount(scoreId);
            if(count==0){
                blockChainDataMapper.insertBlockChainData(chainData);
                scoreMapper.updateScore4(scoreId,3);
            }

        }
    }

    /**
     *      比忘了所有的请求要返回roleType字段，签名时，把签名的数据保存到表中（谁对该成绩签的名 userId,scoreId）
     * @param userId
     * @param roleType
     * @param chainStatus
     * @param schoolId
     * @param pageNo
     * @param pageCount
     * @return
     */
    @Transactional("transactionManager")
    public Map<Integer ,List<Score>> studentChainData2(Integer userId, Integer roleType, Integer chainStatus, Integer schoolId,Integer pageNo,Integer pageCount) {
        List<Score> scores=new ArrayList<>();
        List<Score> scorePages=new ArrayList<>();
        Map<Integer,List<Score>> map = new HashMap<>();
        int count=0;
        StringBuilder phaseIds = new StringBuilder();
        StringBuilder gradeIds = new StringBuilder();
        StringBuilder classIds = new StringBuilder();
        StringBuilder courseIds = new StringBuilder();
        if(roleType==1){//admin
            List<Phase> list=phaseMapper.findPhaseListBySchoolId(schoolId);
            for (Phase phase :list){
                phaseIds.append(phase.getId());
                phaseIds.append(",");
            }
            phaseIds.deleteCharAt(phaseIds.length()-1);
            scorePages=scoreMapper.getScoreByPhaseIds(phaseIds.toString(),chainStatus,(pageNo-1)*pageCount,pageCount,1);//待分页和加上manager_check_status=0的条件
            count=scoreMapper.getScoreByPhaseIdsCount(phaseIds.toString(),chainStatus,1);
        }if(roleType==2){

            /**
             * @aa 当前登陆人 是教育阶段管理者
             * @aa 可能还是年级阶段管理者、班主任、授课老师、监护人、学生 角色
             */
            scores=this.getScoresListByUserIdAndRoleType(roleType,chainStatus,1,userId);
            Collections.sort(scores, (p1, p2) -> p1.getId().compareTo(p2.getId()));
            count=scores.size();
            int a=(pageNo-1)*pageCount;
            int b=a+pageCount;
            scorePages=scores.subList(a, b>count?count:b);
        }if(roleType==3){
            /**
             * @aa 当前登陆人 是教育阶段管理者
             * @aa 可能还是班主任、授课老师、监护人、学生 角色
             */
            scores=this.getScoresListByUserIdAndRoleType(roleType,chainStatus,1,userId);
            Collections.sort(scores, (p1, p2) -> p1.getId().compareTo(p2.getId()));
            count=scores.size();
            int a=(pageNo-1)*pageCount;
            int b=a+pageCount;
            scorePages=scores.subList(a, b>count?count:b);

        }else if(roleType==4||roleType==5){
            //老师或者班主任
            List<UserOrganRole> list3= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,4);//班级id集合
            StringBuilder classIdsForRoleType4 = new StringBuilder();
            //获取 所教班级编号
            for (UserOrganRole userOrganRole:list3){
                classIdsForRoleType4.append(userOrganRole.getClassId());
                classIdsForRoleType4.append(",");
            }
            if(classIdsForRoleType4.length()>0){
                classIdsForRoleType4= classIdsForRoleType4.deleteCharAt(classIdsForRoleType4.length()-1);
            }

            List<UserOrganRole> list4= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,5);//科目id集合
            StringBuilder classIdsForRoleType5 = new StringBuilder();
            StringBuilder courseIdsForRoleType5 = new StringBuilder();
            for (UserOrganRole userOrganRole:list4){
                courseIdsForRoleType5.append(userOrganRole.getCourseId());
                courseIdsForRoleType5.append(",");
                classIdsForRoleType5.append(userOrganRole.getClassId());
                classIdsForRoleType5.append(",");
            }
            if(courseIdsForRoleType5.length()>0){
                courseIdsForRoleType5=  courseIdsForRoleType5.deleteCharAt(courseIdsForRoleType5.length()-1);
                classIdsForRoleType5= classIdsForRoleType5.deleteCharAt(classIdsForRoleType5.length()-1);
            }
            //封装参数
            Map<String,Object> params= Maps.newHashMap();
            params.put("roleType",roleType);
            params.put("classIdsForRoleType4",classIdsForRoleType4);
            params.put("classIdsForRoleType5",classIdsForRoleType5);
            params.put("courseIdsForRoleType5",courseIdsForRoleType5);
            params.put("chainStatus",chainStatus);
            params.put("pageCount",pageCount);
            params.put("pageNo",(pageNo-1)*pageCount);
            params.put("type",1);

            if( list3!=null &&list3.size()>0&&list4!=null &&list4.size()>0){
                /**
                 *@aa  该userId 即是班主任 还是授课老师
                 *@aa 当前登陆人 即是授课老师 还是其他班的班主任  获取该老师所在班的所有学生成绩和该老师所授课科目下的学生成绩
                 */
                scores=scoreMapper.getScoresForTeacherOfRoleType4and5(params);
                //去除重复数据
                scores=this.removeScoreDuplication(scores);
                Collections.sort(scores, (p1, p2) -> p1.getId().compareTo(p2.getId()));
                count=scores.size();
                int a=(pageNo-1)*pageCount;
                int b=a+pageCount;
                scorePages=scores.subList(a, b>count?count:b);

            }else {

                /**
                 *@aa 该userId 对应用户要么是班主任 要么是授课老师
                 *@aa 当前登陆人 是授课老师  获取该老师所教科目下的所有学生成绩
                 *@aa 当前登陆人只是班主任 获取 该老师所在班的学生成绩
                 */
                scorePages=scoreMapper.getScoreByidsForRoleType4or5(params);
                count =scoreMapper.getScoreByidsForRoleType4or5Count(params);
            }

        }else if(roleType==6){//监护人

            scores=this.getScoresListByUserIdAndRoleType(6,chainStatus,1,userId);
            Collections.sort(scores, (p1, p2) -> p1.getId().compareTo(p2.getId()));
            count=scores.size();
            int a=(pageNo-1)*pageCount;
            int b=a+pageCount;
            scorePages=scores.subList(a, b>count?count:b);

        }else if(roleType==7){
            scores=this.getScoresListByUserIdAndRoleType(roleType,chainStatus,1,userId);
            Collections.sort(scores, (p1, p2) -> p1.getId().compareTo(p2.getId()));
            count=scores.size();
            int a=(pageNo-1)*pageCount;
            int b=a+pageCount;
            scorePages=scores.subList(a, b>count?count:b);
        }
        map.put(count,scorePages);
        return map;
    }

    //去重重复数据
    private List<Score> removeScoreDuplication(List<Score> scores) {
        if(scores!=null && scores.size()>0){
            HashMap<Integer,Score> hashMap=new HashMap<>();
            for(Score score:scores){
                hashMap.put(score.getId(),score);
            }
          return new ArrayList<>(hashMap.values());
        }
        return null;
    }

    //获取当前登陆人所管属学生的成绩数据
    private List<Score> getScoresListByUserIdAndRoleType(int roleType, Integer chainStatus, int checkType,Integer userId) {
        String phaseIdsForRoleType2=null;
        String gradeIdsForRoleType3=null;
        String phaseIdsForRoleType3=null;
        String classIdsForRoleType4=null;
        String classIdsForRoleType5=null;
        String courseIdsForRoleType5=null;

        //若当前登陆人是管理者
        if(roleType==2||roleType==3){
            //是否是教育阶段管理者
            phaseIdsForRoleType2=this.getPhaseIdsRorRoleType2(userId,2);

            //是否是年级管理者
            List<String> phaseIdsAndGradeIdsList=this.getPhaseIdsAndGradeIdsList(userId,3);
            if(phaseIdsAndGradeIdsList!=null && phaseIdsAndGradeIdsList.size()>0){
                phaseIdsForRoleType3=phaseIdsAndGradeIdsList.get(0);
                gradeIdsForRoleType3=phaseIdsAndGradeIdsList.get(1);
            }

            //是否是班主任
            classIdsForRoleType4=this.getClassIdsRorRoleType(userId,4);

            //是否是授课老师
            List<String> classIdsAndCourseIdsList=this.getClassIdsAndCourseIdsList(userId,5);
            if(classIdsAndCourseIdsList!=null && classIdsAndCourseIdsList.size()>0){
                classIdsForRoleType5=classIdsAndCourseIdsList.get(0);
                courseIdsForRoleType5=classIdsAndCourseIdsList.get(1);
            }
        }
        //是否是监护人
        List<Object> studentIdList=userMapper.getStudentIdByGuardianId2(userId);
        Integer studentId =null;
        if(studentIdList!=null && studentIdList.size()>0){
            studentId=studentIdList.get(0)!=null?Integer.parseInt(studentIdList.get(0).toString()):null;
        }

        //封装参数
        Map<String,Object> params= Maps.newHashMap();
        params.put("phaseIdsForRoleType2",phaseIdsForRoleType2);
        params.put("gradeIdsForRoleType3",gradeIdsForRoleType3);
        params.put("phaseIdsForRoleType3",phaseIdsForRoleType3);
        params.put("classIdsForRoleType4",classIdsForRoleType4);
        params.put("classIdsForRoleType5",classIdsForRoleType5);
        params.put("courseIdsForRoleType5",courseIdsForRoleType5);
        params.put("chainStatus",chainStatus);
        params.put("type",1);

        //获取成绩数据
        List<Score> scoreListForRoleType2=null;
        List<Score> scoreListForRoleType3=null;
        List<Score> scoreListForRoleType4=null;
        List<Score> scoreListForRoleType5=null;
        List<Score> scoreListForRoleType6=null;
        List<Score> scoreListForRoleType7=null;

        //条件检索 获取学生成绩
        if(roleType==2||roleType==3) {
            if (StringUtils.isNotBlank(phaseIdsForRoleType2)) {
                params.put("roleType", 2);
                scoreListForRoleType2 = scoreMapper.getScoresWithConditionalByRoleType(params);
                //scoreListForRoleType2 = scoreMapper.getScoresWithConditionalByRoleType2(params);
            }
            if (StringUtils.isNotBlank(gradeIdsForRoleType3)) {
                params.put("roleType", 3);
                scoreListForRoleType3 = scoreMapper.getScoresWithConditionalByRoleType(params);
                //scoreListForRoleType3 = scoreMapper.getScoresWithConditionalByRoleType3(params);
            }

            if (StringUtils.isNotBlank(classIdsForRoleType4)) {
                params.put("roleType", 4);
                scoreListForRoleType4 = scoreMapper.getScoresWithConditionalByRoleType(params);
               // scoreListForRoleType4 = scoreMapper.getScoresWithConditionalByRoleType4(params);
            }
            if (StringUtils.isNotBlank(courseIdsForRoleType5)) {
                params.put("roleType", 5);
                scoreListForRoleType5 = scoreMapper.getScoresWithConditionalByRoleType(params);
               // scoreListForRoleType5 = scoreMapper.getScoresWithConditionalByRoleType5(params);
            }
        }
        if(studentId==null || studentId==0 ){
            //不是监护人 是不是学生呢
            int stuCount=userOrganRoleMapper.getCountRecordWithUserIdAndRoleType(userId,7);
            if(stuCount>0){
                params.put("roleType",7);
                params.put("studentId",userId);
                scoreListForRoleType7=scoreMapper.getScoresWithConditionalByRoleType(params);
                //scoreListForRoleType7=scoreMapper.getScoresWithConditionalByRoleType7(params);
            }
        }else{
            params.put("roleType",6);
            params.put("studentId",studentId);
            scoreListForRoleType6=scoreMapper.getScoresWithConditionalByRoleType(params);
            //scoreListForRoleType6=scoreMapper.getScoresWithConditionalByRoleType6(params);
        }

        //把成绩封装到集合中
        List<Score> scores=new ArrayList<Score>();
        if(roleType==2||roleType==3){
            List<Score> managerScores=new ArrayList<>();
            List<Score> teacherScores=new ArrayList<>();

            // 此用户是教育阶段管理者还是年级管理者
            if(scoreListForRoleType2!=null &&scoreListForRoleType2.size()>0 && scoreListForRoleType3!=null && scoreListForRoleType3.size()>0){
                //去除重复数据
                managerScores.addAll(scoreListForRoleType2);
                managerScores.addAll(scoreListForRoleType3);

                managerScores=this.removeScoreDuplication(managerScores);
            }else {
                if(scoreListForRoleType2!=null && scoreListForRoleType2.size()>0){
                    scores.addAll(scoreListForRoleType2);
                }
                if(scoreListForRoleType3!=null && scoreListForRoleType3.size()>0){
                    scores.addAll(scoreListForRoleType3);
                }
            }

            // 此用户是班主任还是授课老师
            if(scoreListForRoleType4!=null &&scoreListForRoleType4.size()>0 &&scoreListForRoleType5!=null && scoreListForRoleType5.size()>0){
                teacherScores.addAll(scoreListForRoleType4);
                teacherScores.addAll(scoreListForRoleType5);

                teacherScores=this.removeScoreDuplication(teacherScores);
            }else {
                if(scoreListForRoleType4!=null && scoreListForRoleType4.size()>0){
                    scores.addAll(scoreListForRoleType4);
                }
                if(scoreListForRoleType5!=null && scoreListForRoleType5.size()>0){
                    scores.addAll(scoreListForRoleType5);
                }
            }

            if(managerScores.size()>0){
                scores.addAll(managerScores);
            }
            if(teacherScores.size()>0){
                scores.addAll(teacherScores);
            }
        }
        if(scoreListForRoleType6!=null && scoreListForRoleType6.size()>0){
            scores.addAll(scoreListForRoleType6);
        }
        if(scoreListForRoleType7!=null && scoreListForRoleType7.size()>0){
            scores.addAll(scoreListForRoleType7);
        }
        return scores;
    }

    private List<String> getClassIdsAndCourseIdsList(Integer userId, int roleType) {
        List<UserOrganRole> list4= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,roleType);
        StringBuilder classIdsForRoleType5 = new StringBuilder();
        StringBuilder courseIdsForRoleType5 = new StringBuilder();
        for (UserOrganRole userOrganRole:list4){
            courseIdsForRoleType5.append(userOrganRole.getCourseId());
            courseIdsForRoleType5.append(",");
            classIdsForRoleType5.append(userOrganRole.getClassId());
            classIdsForRoleType5.append(",");
        }
        if(courseIdsForRoleType5.length()>0){
            classIdsForRoleType5.deleteCharAt(classIdsForRoleType5.length()-1);
            courseIdsForRoleType5.deleteCharAt(courseIdsForRoleType5.length()-1);
            if(courseIdsForRoleType5.length()>0){
                List<String> classIdsAndCourseIdsList=new ArrayList<String>();
                classIdsAndCourseIdsList.add(classIdsForRoleType5.toString());
                classIdsAndCourseIdsList.add(courseIdsForRoleType5.toString());

                return classIdsAndCourseIdsList;
            }
        }

        return null;
    }

    private String getClassIdsRorRoleType(Integer userId, int roleType) {
        List<UserOrganRole> list3= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,roleType);
        StringBuilder classIdsForRoleType4 = new StringBuilder();
        for (UserOrganRole userOrganRole:list3){
            classIdsForRoleType4.append(userOrganRole.getClassId());
            classIdsForRoleType4.append(",");
        }
        if(classIdsForRoleType4.length()>0){
            classIdsForRoleType4.deleteCharAt(classIdsForRoleType4.length()-1);
            if(classIdsForRoleType4.length()>0){
                return classIdsForRoleType4.toString();
            }
        }

        return null;
    }

    private List<String> getPhaseIdsAndGradeIdsList(Integer userId, int roleType) {
        List<UserOrganRole> list2= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,roleType);//年级id集合
        StringBuilder gradeIdsForRoleType3 = new StringBuilder();
        StringBuilder phaseIdsForRoleType3 = new StringBuilder();
        for (UserOrganRole userOrganRole:list2){
            gradeIdsForRoleType3.append(userOrganRole.getGradeId());
            gradeIdsForRoleType3.append(",");

            phaseIdsForRoleType3.append(userOrganRole.getPhaseId());
            phaseIdsForRoleType3.append(",");
        }
        if(gradeIdsForRoleType3.length()>0){
            gradeIdsForRoleType3.deleteCharAt(gradeIdsForRoleType3.length()-1);
            phaseIdsForRoleType3.deleteCharAt(phaseIdsForRoleType3.length()-1);
            if(gradeIdsForRoleType3.length()>0){
                List<String> phaseIdsAndGradeIdsList=new ArrayList<String>();
                phaseIdsAndGradeIdsList.add(phaseIdsForRoleType3.toString());
                phaseIdsAndGradeIdsList.add(gradeIdsForRoleType3.toString());

                return phaseIdsAndGradeIdsList;
            }
        }

        return null;
    }

    //获取教育阶段管理者 所在教育阶段编号
    private String getPhaseIdsRorRoleType2(Integer userId, int roleType) {
        List<UserOrganRole> list1= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,roleType);//教育阶段id集合
        StringBuilder phaseIdsForRoleType2 = new StringBuilder();
        for (UserOrganRole userOrganRole:list1){
            phaseIdsForRoleType2.append(userOrganRole.getPhaseId());
            phaseIdsForRoleType2.append(",");
        }
        if(phaseIdsForRoleType2.length()>0){
            phaseIdsForRoleType2= phaseIdsForRoleType2.deleteCharAt(phaseIdsForRoleType2.length()-1);
           if(phaseIdsForRoleType2.length()>0){
               return phaseIdsForRoleType2.toString();
           }
        }
        return null;
    }

    /**
     *      比忘了所有的请求要返回roleType字段，签名时，把签名的数据保存到表中（谁对该成绩签的名 userId,scoreId）
     * @param userId
     * @param roleType
     * @param chainStatus
     * @param schoolId
     * @param pageNo
     * @param pageCount
     * @return
     */
    @Transactional("transactionManager")
    public Map<Integer ,List<Score>> studentChainData2_old(Integer userId, Integer roleType, Integer chainStatus, Integer schoolId,Integer pageNo,Integer pageCount) {
        List<Score> scores=new ArrayList<>();
        List<Score> scorePages=new ArrayList<>();
        Map<Integer,List<Score>> map = new HashMap<>();
        int count=0;
        StringBuilder phaseIds = new StringBuilder();
        StringBuilder gradeIds = new StringBuilder();
        StringBuilder classIds = new StringBuilder();
        StringBuilder courseIds = new StringBuilder();
        if(roleType==1){//admin
            List<Phase> list=phaseMapper.findPhaseListBySchoolId(schoolId);
            for (Phase phase :list){
                phaseIds.append(phase.getId());
                phaseIds.append(",");
            }
            phaseIds.deleteCharAt(phaseIds.length()-1);
            scorePages=scoreMapper.getScoreByPhaseIds(phaseIds.toString(),chainStatus,(pageNo-1)*pageCount,pageCount,1);//待分页和加上manager_check_status=0的条件
            count=scoreMapper.getScoreByPhaseIdsCount(phaseIds.toString(),chainStatus,1);
        }if(roleType==2){
            //管理者（一层管理者或二层管理者）
            List<UserOrganRole> list1= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,2);//教育阶段id集合
            for (UserOrganRole userOrganRole:list1){
                phaseIds.append(userOrganRole.getPhaseId());
                phaseIds.append(",");
            }
            phaseIds.deleteCharAt(phaseIds.length()-1);


            List<UserOrganRole> list2= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,3);//年级id集合
            for (UserOrganRole userOrganRole:list2){
                gradeIds.append(userOrganRole.getGradeId());
                gradeIds.append(",");
            }
            if(gradeIds.length()>0){
                gradeIds.deleteCharAt(gradeIds.length()-1);
            }
            Integer status=0;
            if(gradeIds.length()>0){
                status=3;
            }else{
                status=4;
            }
            List<Score> scoreList1=scoreMapper.getScoreByids3(status,null,null,gradeIds.toString(),phaseIds.toString(),chainStatus,null,null,1);//待加上manager_check_status=0的条件
            //老师或者班主任
            List<UserOrganRole> list3= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,4);//班级id集合
            for (UserOrganRole userOrganRole:list3){
                classIds.append(userOrganRole.getClassId());
                classIds.append(",");
            }
            if(classIds.length()>0){
                classIds.deleteCharAt(classIds.length()-1);
            }

            List<UserOrganRole> list4= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,5);//科目id集合
            for (UserOrganRole userOrganRole:list4){
                courseIds.append(userOrganRole.getCourseId());
                courseIds.append(",");
            }
            if(courseIds.length()>0){
                courseIds.deleteCharAt(courseIds.length()-1);
            }
            status=0;
            if(classIds.length()>0&&courseIds.length()>0){
                status=1;
            }else if(classIds.length()>0&&courseIds.length()==0){
                status=2;
            }else if(classIds.length()==0&&courseIds.length()>0){
                status=3;
            }
            List<Score> scoreList2=new ArrayList<>();
            if(status!=0){
                scoreList2=scoreMapper.getScoreByids5(status,classIds.length()>0?classIds.toString():null,courseIds.length()>0?courseIds.toString():null,chainStatus,null,null,1);//待加上instructor_check_status=0的条件
            }
            //监护人
            User user =userMapper.getUserById(userId);
            List<Score> scoreList3= new ArrayList<>();
            if(user.getStudentId()!=null&&!"".equals(user.getStudentId())){
                scoreList3=scoreMapper.getScoreByUserId(user.getStudentId(),chainStatus,null,null,1);//加上guardian_check_status=0的条件
            }
            scores.addAll(scoreList1);
            scores.addAll(scoreList2);
            scores.addAll(scoreList3);
            Collections.sort(scores, (p1, p2) -> p1.getId().compareTo(p2.getId()));
            count=scores.size();
            int a=(pageNo-1)*pageCount;
            int b=a+pageCount;
            scorePages=scores.subList(a, b>count?count:b);
        }if(roleType==3){
            List<UserOrganRole> list2= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,3);//年级id集合
            for (UserOrganRole userOrganRole:list2){
                gradeIds.append(userOrganRole.getGradeId());
                gradeIds.append(",");
            }
            if(gradeIds.length()>0){
                gradeIds.deleteCharAt(gradeIds.length()-1);
            }
            Integer status=4;
            scores=scoreMapper.getScoreByids4(status,null,null,gradeIds.toString(),chainStatus,null,null,1);

            //老师或者班主任
            List<UserOrganRole> list3= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,4);//班级id集合
            for (UserOrganRole userOrganRole:list3){
                classIds.append(userOrganRole.getClassId());
                classIds.append(",");
            }
            if(classIds.length()>0){
                classIds.deleteCharAt(classIds.length()-1);
            }

            List<UserOrganRole> list4= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,5);//科目id集合
            for (UserOrganRole userOrganRole:list4){
                courseIds.append(userOrganRole.getCourseId());
                courseIds.append(",");
            }
            if(courseIds.length()>0){
                courseIds.deleteCharAt(courseIds.length()-1);
            }
            status=0;
            if(classIds.length()>0&&courseIds.length()>0){
                status=1;
            }else if(classIds.length()>0&&courseIds.length()==0){
                status=2;
            }else if(classIds.length()==0&&courseIds.length()>0){
                status=3;
            }
            List<Score> scoreList2= new ArrayList<>();
            if(status!=0){
                scoreList2=scoreMapper.getScoreByids5(status,classIds.length()>0?classIds.toString():null,courseIds.length()>0?courseIds.toString():null,chainStatus,null,null,1);//待加上instructor_check_status=0的条件
            }
            //监护人
            User user =userMapper.getUserById(userId);
            List<Score> scoreList3= new ArrayList<>();
            if(user.getStudentId()!=null&&!"".equals(user.getStudentId())){
                scoreList3=scoreMapper.getScoreByUserId(user.getStudentId(),chainStatus,null,null,1);
            }
            scores.addAll(scoreList2);
            scores.addAll(scoreList3);
            count=scores.size();
            Collections.sort(scores, (p1, p2) -> p1.getId().compareTo(p2.getId()));
            int a=(pageNo-1)*pageCount;
            int b=a+pageCount;
            scorePages=scores.subList(a, b>count?count:b);
        }else if(roleType==4||roleType==5){
            //老师或者班主任

            List<UserOrganRole> list3= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,4);//班级id集合
            for (UserOrganRole userOrganRole:list3){
                classIds.append(userOrganRole.getClassId());
                classIds.append(",");
            }
            if(classIds.length()>0){
                classIds.deleteCharAt(classIds.length()-1);
            }

            List<UserOrganRole> list4= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,5);//科目id集合
            for (UserOrganRole userOrganRole:list4){
                courseIds.append(userOrganRole.getCourseId());
                courseIds.append(",");
            }
            if(courseIds.length()>0){
                courseIds.deleteCharAt(courseIds.length()-1);
            }
            Integer status=0;
            if(classIds.length()>0&&courseIds.length()>0){
                status=1;
            }else if(classIds.length()>0&&courseIds.length()==0){
                status=2;
            }else if(classIds.length()==0&&courseIds.length()>0){
                status=3;
            }
             scorePages=scoreMapper.getScoreByids5(status,classIds.length()>0?classIds.toString():null,courseIds.length()>0?courseIds.toString():null,chainStatus,(pageNo-1)*pageCount,pageCount,1);//待加分页和instructor_check_status=0的条件
             count =scoreMapper.getScoreByids5Count(status,classIds.length()>0?classIds.toString():null,courseIds.length()>0?courseIds.toString():null,chainStatus,1);

        }else if(roleType==6){//监护人
            User user =userMapper.getUserById(userId);
            scorePages=scoreMapper.getScoreByUserId(user.getStudentId(),chainStatus,(pageNo-1)*pageCount,pageCount,1);//待加分页
            count=scoreMapper.getScoreByUserIdCount(user.getStudentId(),chainStatus,1);
        }else if(roleType==7){
            User user =userMapper.getUserById(userId);
            scorePages=scoreMapper.getScoreByUserId(user.getId(),chainStatus,(pageNo-1)*pageCount,pageCount,1);//待加分页
            count=scoreMapper.getScoreByUserIdCount(user.getId(),chainStatus,1);
        }
        map.put(count,scorePages);
        return map;
    }




    @Transactional("transactionManager")
    public List<Score>  studentChainData3(Integer userId,Integer pageNo,Integer pageCount) {
        return scoreMapper.studentChainData3(userId,(pageNo-1)*pageCount,pageCount);
    }@Transactional("transactionManager")
    public int studentChainData3Count(Integer userId) {
        return scoreMapper.studentChainData3Count(userId);
    }
    @Transactional("transactionManager")
    public Score  getScoreById(Integer scoreId) {
        return scoreMapper.getScoreById(scoreId);
    }

    /**
     * 登录时提供的该用户的待签名书数量
     * @param userId
     * @param roleType
     * @param schoolId
     * @return
     */
    @Transactional("transactionManager")
    public Integer  studentChainDataCount(Integer userId, Integer roleType, Integer schoolId) {
        Calendar cal = Calendar.getInstance();//使用默认时区和语言环境获得一个日历。
        cal.add(Calendar.DAY_OF_MONTH, -5);//取当前日期的前5天.
        //把已过期的学生成绩数据修改状态
        scoreService.updateScoreChainStatusByDate(4,sdf.format(cal.getTime()));
        Integer toBeSignCount=0;
        List<Score> scores=new ArrayList<>();
        StringBuilder phaseIds = new StringBuilder();
        StringBuilder gradeIds = new StringBuilder();
        StringBuilder classIds = new StringBuilder();
        StringBuilder courseIds = new StringBuilder();
        if(roleType==1){//admin
            List<Phase> list=phaseMapper.findPhaseListBySchoolId(schoolId);
            for (Phase phase :list){
                phaseIds.append(phase.getId());
                phaseIds.append(",");
            }
            if(phaseIds.length()!=0){
                phaseIds.deleteCharAt(phaseIds.length()-1);

            scores=scoreMapper.getScoreByPhaseIds(phaseIds.toString(),1,null,null,1);//待分页和加上manager_check_status=0的条件
            if(scores!=null){
                toBeSignCount=scores.size();
            }
         }
        }if(roleType==2){
            //管理者（一层管理者或二层管理者）
            List<UserOrganRole> list1= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,2);//教育阶段id集合
            for (UserOrganRole userOrganRole:list1){
                phaseIds.append(userOrganRole.getPhaseId());
                phaseIds.append(",");
            }
            phaseIds.deleteCharAt(phaseIds.length()-1);


            List<UserOrganRole> list2= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,3);//年级id集合
            for (UserOrganRole userOrganRole:list2){
                gradeIds.append(userOrganRole.getGradeId());
                gradeIds.append(",");
            }
            if(gradeIds.length()>0){
                gradeIds.deleteCharAt(gradeIds.length()-1);
            }
            Integer status=0;
            if(gradeIds.length()>0){
                status=3;
            }else{
                status=4;
            }
            List<Score> scoreList1=scoreMapper.getScoreByids3(status,null,null,gradeIds.toString(),phaseIds.toString(),1,null,null,1);//待加上manager_check_status=0的条件
            //老师或者班主任
            List<UserOrganRole> list3= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,4);//班级id集合
            for (UserOrganRole userOrganRole:list3){
                classIds.append(userOrganRole.getClassId());
                classIds.append(",");
            }
            if(classIds.length()>0){
                classIds.deleteCharAt(classIds.length()-1);
            }

            List<UserOrganRole> list4= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,5);//科目id集合
            for (UserOrganRole userOrganRole:list4){
                courseIds.append(userOrganRole.getCourseId());
                courseIds.append(",");
            }
            if(courseIds.length()>0){
                courseIds.deleteCharAt(courseIds.length()-1);
            }
            if(classIds.length()>0&&courseIds.length()>0){
                status=1;
            }else if(classIds.length()>0&&courseIds.length()==0){
                status=2;
            }else if(classIds.length()==0&&courseIds.length()>0){
                status=3;
            }else if(classIds.length()==0&&courseIds.length()==0){
                status=4;
            }
            List<Score> scoreList2= new ArrayList<>();
            if(status!=4){
                scoreList2=scoreMapper.getScoreByids5(status,classIds.length()>0?classIds.toString():null,courseIds.length()>0?courseIds.toString():null,1,null,null,1);
            }
            //监护人
            User user =userMapper.getUserById(userId);
            List<Score> scoreList3=scoreMapper.getScoreByUserId(user.getStudentId(),1,null,null,1);
            if(scoreList1!=null){
                toBeSignCount=toBeSignCount+scoreList1.size();
            }if(scoreList2!=null){
                toBeSignCount=toBeSignCount+scoreList2.size();
            }if(scoreList3!=null){
                toBeSignCount=toBeSignCount+scoreList3.size();
            }
        }if(roleType==3){
            List<UserOrganRole> list2= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,3);//年级id集合
            for (UserOrganRole userOrganRole:list2){
                gradeIds.append(userOrganRole.getGradeId());
                gradeIds.append(",");
            }
            if(gradeIds.length()>0){
                gradeIds.deleteCharAt(gradeIds.length()-1);
            }
            Integer status=4;
            scores=scoreMapper.getScoreByids4(status,null,null,gradeIds.toString(),1,null,null,1);

            //老师或者班主任
            List<UserOrganRole> list3= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,4);//班级id集合
            for (UserOrganRole userOrganRole:list3){
                classIds.append(userOrganRole.getClassId());
                classIds.append(",");
            }
            if(classIds.length()>0){
                classIds.deleteCharAt(classIds.length()-1);
            }

            List<UserOrganRole> list4= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,5);//科目id集合
            for (UserOrganRole userOrganRole:list4){
                courseIds.append(userOrganRole.getCourseId());
                courseIds.append(",");
            }
            if(courseIds.length()>0){
                courseIds.deleteCharAt(courseIds.length()-1);
            }
            if(classIds.length()>0&&courseIds.length()>0){
                status=1;
            }else if(classIds.length()>0&&courseIds.length()==0){
                status=2;
            }else if(classIds.length()==0&&courseIds.length()>0){
                status=3;
            }else if(classIds.length()==0&&courseIds.length()==0){
                status=4;
            }
            List<Score> scoreList2= new ArrayList<>();
            if(status!=4){
                scoreList2=scoreMapper.getScoreByids5(status,classIds.length()>0?classIds.toString():null,courseIds.length()>0?courseIds.toString():null,1,null,null,1);

            }
            //监护人
            User user =userMapper.getUserById(userId);
            List<Score> scoreList3=scoreMapper.getScoreByUserId(user.getStudentId(),1,null,null,1);
            if(scoreList2!=null){
                toBeSignCount=toBeSignCount+scoreList2.size();
            }if(scoreList3!=null){
                toBeSignCount=toBeSignCount+scoreList3.size();
            }
        }else if(roleType==4||roleType==5){
            //老师或者班主任
            List<UserOrganRole> list3= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,4);//班级id集合
            for (UserOrganRole userOrganRole:list3){
                classIds.append(userOrganRole.getClassId());
                classIds.append(",");
            }
            if(classIds.length()>0){
                classIds.deleteCharAt(classIds.length()-1);
            }

            List<UserOrganRole> list4= userOrganRoleMapper.findUserOrganRoleByRoleAndUserId(userId,5);//科目id集合
            for (UserOrganRole userOrganRole:list4){
                courseIds.append(userOrganRole.getCourseId());
                courseIds.append(",");
            }
            if(courseIds.length()>0){
                courseIds.deleteCharAt(courseIds.length()-1);
            }
            Integer status=0;
            if(classIds.length()>0&&courseIds.length()>0){
                status=1;
            }else if(classIds.length()>0&&courseIds.length()==0){
                status=2;
            }else if(classIds.length()==0&&courseIds.length()>0){
                status=3;
            }
            scores=scoreMapper.getScoreByids5(status,classIds.length()>0?classIds.toString():null,courseIds.length()>0?courseIds.toString():null,1,null,null,1);
          if(scores!=null){
              toBeSignCount=scores.size();
          }
        }else if(roleType==6){//监护人
            User user =userMapper.getUserById(userId);
            scores=scoreMapper.getScoreByUserId(user.getStudentId(),1,null,null,1);
            toBeSignCount=scores.size();
        }else if(roleType==7){
            User user =userMapper.getUserById(userId);
            scores=scoreMapper.getScoreByUserId(user.getId(),1,null,null,1);
            if(scores!=null){
                toBeSignCount=scores.size();
            }
        }
        return toBeSignCount;
    }

    @Transactional("transactionManager")
    public int  updateScoreChainStatusByDate(Integer chainStatus,String expiryTime ) {
        return scoreMapper.updateScoreChainStatusByDate(chainStatus,expiryTime);
    }

    public int updateScoreCheckStatusByScoreId(Integer scoreId,String currentDate,String recordTime) {
      return  scoreMapper.updateScoreCheckStatusByScoreId(scoreId,currentDate,recordTime);
    }
}
